<!-- src/views/operations/ProductSelectionDialog.vue -->
<template>
  <el-dialog
    v-model="visible"
    :title="title"
    width="80%"
    @close="handleClose"
  >
    <div class="product-selection-container">
      <div class="search-toolbar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="批次号">
            <el-input 
              v-model="searchForm.batchNumber" 
              placeholder="请输入" 
              clearable 
              style="width: 180px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
            <el-button icon="Refresh" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table 
        :data="productList"
        style="width: 100%; margin-top: 20px;"
        border
        stripe
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" :selectable="checkSelectable" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="code" label="商品编码" min-width="120" />
        <el-table-column prop="title" label="商品名称" min-width="150" />
        <el-table-column prop="batchNumber" label="批次号" min-width="120" />
        <el-table-column prop="consignorName" label="货主" min-width="100" />
        <el-table-column prop="supplierName" label="供应商" min-width="120" />
        <el-table-column prop="realArrivalTime" label="实际到达时间" min-width="160" />
        <el-table-column prop="count" label="数量" min-width="80" align="center" />
        <el-table-column prop="warehouseName" label="仓库" min-width="100" />
        <el-table-column prop="warehouseAreaName" label="库区" min-width="100" />
        <el-table-column prop="warehouseAreaLocaName" label="库位" min-width="100" />
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag type="success">{{ formatStatus(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 40]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; justify-content: flex-end;"
        />
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUpPageApi } from '@/api/warehousingEntryUp'
import { ElMessage } from 'element-plus'

const emits = defineEmits(['confirm', 'close'])

// 弹窗状态
const visible = ref(false)

// 弹窗标题
const title = ref('选择商品')

// 表格数据
const productList = ref([])
const loading = ref(false)

// 分页数据
const page = ref(1)
const pageSize = ref(10)
const totalSize = ref(0)

// 搜索表单
const searchForm = ref({
  batchNumber: '',
  status: 6  // 默认状态设置为6（已上架）
})

// 选中的行数据
const selectedRows = ref([])

// 选择模式（single-单选，multiple-多选）
const selectionMode = ref('multiple')

// 打开弹窗
const open = (options = {}) => {
  title.value = options.title || '选择商品'
  selectionMode.value = options.selectionMode || 'multiple'
  visible.value = true
  getProductList()
}

// 关闭弹窗
const handleClose = () => {
  visible.value = false
  emits('close')
}

// 确认选择
const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个商品')
    return
  }
  
  // 处理选中的数据，添加count字段用于后续修改
  const selectedData = selectedRows.value.map(item => ({
    ...item,
    id: item.id,
    code: item.code,
    name: item.title,
    specCode: '', // 规格编码需要从其他接口获取或手动填写
    count: item.count, // 原始数量
    originalCount: item.count // 保存原始数量用于校验
  }))
  
  emits('confirm', selectedData)
  handleClose()
}

// 获取商品列表
const getProductList = async () => {
  loading.value = true
  try {
    const res = await getUpPageApi(page.value, pageSize.value, searchForm.value.status, searchForm.value.batchNumber)
    productList.value = res.data.rows
    totalSize.value = res.data.total
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  page.value = 1
  getProductList()
}

// 重置搜索
const reset = () => {
  searchForm.value.batchNumber = ''
  page.value = 1
  getProductList()
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  page.value = 1
  getProductList()
}

const handleCurrentChange = (val) => {
  page.value = val
  getProductList()
}

// 处理选择变化
const handleSelectionChange = (val) => {
  // 如果是单选模式，只保留最后一个选择的项
  if (selectionMode.value === 'single') {
    selectedRows.value = val.length > 0 ? [val[val.length - 1]] : []
  } else {
    selectedRows.value = val
  }
}

// 检查是否可选择（用于表格选择控制）
const checkSelectable = (row, index) => {
  // 可以添加额外的选择条件
  return true
}

// 格式化状态
const formatStatus = (status) => {
  const statusMap = {
    1: '未到货',
    2: '已到货',
    3: '已卸货',
    4: '分拣中',
    5: '已上架',
    6: '已上架'
  }
  return statusMap[status] || '未知状态'
}

// 暴露方法
defineExpose({
  open,
  close: handleClose
})
</script>

<style scoped>
.product-selection-container {
  padding: 10px;
}

.search-toolbar {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
}

.search-form :deep(.el-form-item__label) {
  font-weight: normal;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>